#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>

const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 4, 1);
DNSServer dnsServer;
ESP8266WebServer webServer(80);

int debug = 1;
void setup() {
  pinMode(D2, OUTPUT); 
  
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("little-match");

  dnsServer.setTTL(300);

  dnsServer.setErrorReplyCode(DNSReplyCode::ServerFailure);

  // 无法在win10环境下正常运作,但使用安卓手机正常
  dnsServer.start(DNS_PORT, "*", apIP);

  webServer.onNotFound([]() {
    String message;
    message += "<form action=\"/LED\" method=\"POST\">";
    message += "<input style=\"font-size: 25px; width: 100%; height: 200px; margin-top: 40%;"; 
    message += "border-radius: 5px;\"type=\"submit\" value=\"LED Button\">";
    message += "</form>";
    webServer.send(200, "text/html", message);
  });

  webServer.on("/LED", handleLEDRsp);
  webServer.begin();
}

void handleLEDRsp() {
    /* change LED state */
    digitalWrite(D2,!digitalRead(D2));
    webServer.sendHeader("Location","/");
    webServer.send(303);

    if(debug){
        Serial.print("Http Server: ");
        Serial.println("Response client request for LED button");
    }
}

void loop() {
  dnsServer.processNextRequest();
  webServer.handleClient();
}
